﻿namespace Nomo.UnityCoreModule.Waiters
{
    /// <summary>
    /// 进度等待器。
    /// </summary>
    public sealed class ProgressWaiter : Waiter
    {
        private readonly TimeWaiter           _timeWaiter;
        private readonly System.Action<float> _onProgressUpdateAction;

        internal ProgressWaiter(TimeWaiter timeWaiter, System.Action<float> onProgressUpdateAction)
        {
            _timeWaiter             = timeWaiter             ?? throw new System.ArgumentNullException(nameof(timeWaiter));
            _onProgressUpdateAction = onProgressUpdateAction ?? throw new System.ArgumentNullException(nameof(onProgressUpdateAction));
        }

        /// <inheritdoc />
        public override bool MoveNext()
        {
            return !Completed && base.MoveNext();
        }

        private protected override bool KeepWaiting
        {
            get
            {
                var currentTime = _timeWaiter.InternalGetCurrentTime;
                var waitTime    = _timeWaiter.InternalGetWaitTime;
                _timeWaiter.MoveNext();
                _onProgressUpdateAction(currentTime < waitTime ? currentTime / waitTime : 1F);
                return !_timeWaiter.Completed;
            }
        }

        /// <inheritdoc />
        public override void Reset()
        {
            base.Reset();
            _timeWaiter.Reset();
            _onProgressUpdateAction(default);
        }
    }
}
